package com.bj58.mis.apm.apm.scf.service.impl;


import com.bj58.data.roc.service.cube.CubeService;
import com.bj58.data.roc.service.cube.CubeStep4Service;
import com.bj58.data.roc.service.cube.model.Cube;
import com.bj58.data.roc.service.cube.model.step4.CubeInfo;
import com.bj58.data.roc.service.project.model.CubeBase;
import com.bj58.data.roc.service.project.model.Project;
import com.bj58.mis.apm.apm.scf.mapper.*;
import com.bj58.mis.apm.apm.scf.module.*;
import com.bj58.mis.apm.apm.scf.service.AuthService;
import com.bj58.mis.apm.apm.scf.util.FileUtil;
import com.bj58.spat.scf.client.SCFInit;
import com.bj58.spat.scf.client.proxy.builder.ProxyFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangyu84
 * @create 2018/7/6
 * @since 1.0.0
 */
@Service
@Transactional
public class AuthServiceImpl implements AuthService {
    @Autowired
    private KylinCubeRepository kylinCubeRepository;
    @Autowired
    private KylinProjectRepository kylinProjectRepository;
    @Autowired
    private RocAuthCubeRepository rocAuthCubeRepository;
    @Autowired
    private RocAuthProjectRepository rocAuthProjectRepository;
    @Autowired
    private RocUserRepository rocUserRepository;

    @Override
    public void auth(List<CubeBase> cubeBaseList, List<Project> projectList, CubeStep4Service cubeStep4Service) {
        //需要保存的RocAuthProject
        List<RocAuthProject> authProjects = new ArrayList<>();
        //需要保存的RocAuthCube
        List<RocAuthCube> authCubes = new ArrayList<>();
        //需要保存的RocUser
        List<RocUser> rocUsers = new ArrayList<>();

        //需要删除的RocAuthProjct
        List<RocAuthProject> delAuthProjects = new ArrayList<>();
        //需要删除的RocAuthCube
        List<RocAuthCube> delAuthCubes = new ArrayList<>();
        //需要删除的RocUser
        // List<RocUser> delRocUsers=new ArrayList<>();

        //数据库的RocAuthProject
        List<RocAuthProject> dbAuthProjects = rocAuthProjectRepository.findAll();
        //数据库的RocAuthCube
        List<RocAuthCube> dbAuthCubes = rocAuthCubeRepository.findAll();


        Map<String, List<RocAuthProject>> projectMap = new HashMap<>(dbAuthProjects.size() != 0 ? dbAuthProjects.size() : 2);
        Map<String, List<RocAuthCube>> cubeMap = new HashMap<>(dbAuthCubes.size() != 0 ? dbAuthCubes.size() : 2);

        for (RocAuthProject authProject : dbAuthProjects) {
            if (!projectMap.containsKey(authProject.getProjectName())) {
                projectMap.put(authProject.getProjectName(), new ArrayList<>());
            }
            projectMap.get(authProject.getProjectName()).add(authProject);
        }

        for (RocAuthCube authCube : dbAuthCubes) {
            if (!cubeMap.containsKey(authCube.getAa())) {
                cubeMap.put(authCube.getAa(), new ArrayList<>());
            }
            cubeMap.get(authCube.getAa()).add(authCube);
        }
        //projects key为name value为Id
        Map<String, String> projects = new HashMap<>(projectList.size());
        //owners key为name value为RocUser对象
        Map<String, RocUser> owners = new HashMap<>(128);
        for (Project project : projectList) {
            String authProjectName = project.getNameEn();
            //用户
            if (StringUtils.isNotBlank(project.getOwner())) {
                for (String owner : project.getOwner().split(",")) {
                    if (!owners.containsKey(owner)) {
                        RocUser rocUser = new RocUser(owner, null);
                        owners.put(owner, rocUser);
                    }
                }
            }
            if (Integer.valueOf(project.getDeleted()) == 0) {
                String modifiedTime = DateFormatUtils.format(project.getModifyTime(), "yyyy-MM-dd HH:mm:ss");
                //project有原始数据
                if (projectMap.containsKey(authProjectName)) {
                    //有过更新
                    if (!isDateEquals(projectMap.get(authProjectName).get(0).getLastModified(), modifiedTime)) {
                        //将数据库原有数据放进待删除列表
                        delAuthProjects.addAll(projectMap.get(authProjectName));
                        // projectMap移除
                        projectMap.remove(authProjectName);
                    } else {
                        // projectMap移除
                        projectMap.remove(authProjectName);
                        //跳过本次循环
                        continue;
                    }

                }
                //新添加project 或者 project有过修改
                KylinProject kp=kylinProjectRepository.getByNameAndDeleted(authProjectName, 0);
                if(kp==null){
                    continue;
                }
                String authProjectId =kp.getId();
                projects.put(authProjectName, authProjectId);
                if (StringUtils.isNotBlank(project.getOwner())) {
                    for (String owner : project.getOwner().split(",")) {
                        RocAuthProject authProject = new RocAuthProject(owner, authProjectId, authProjectName,project.getNameCn(), DateFormatUtils.format(project.getCreateTime(), "yyyy-MM-dd HH:mm:ss"), modifiedTime);
                        //修改后的数据放进添加列表
                        authProjects.add(authProject);
                    }
                }

            } else {
                if (projectMap.containsKey(authProjectName)) {
                    //将数据库原有数据放进待删除列表
                    delAuthProjects.addAll(projectMap.get(authProjectName));
                    // projectMap移除
                    projectMap.remove(authProjectName);
                }
            }

        }
        for (String key : projectMap.keySet()) {
            delAuthProjects.addAll(projectMap.get(key));
        }

        if (delAuthProjects.size() != 0) {
            //删除roc_auth_project表数据
            rocAuthProjectRepository.deleteInBatch(delAuthProjects);
        }
        if (authProjects.size() != 0) {
            //添加roc_auth_project表数据
            rocAuthProjectRepository.saveAll(authProjects);
        }

        for (CubeBase cubeBase : cubeBaseList) {
            String authCubeName = cubeBase.getCubeName() + "_" + cubeBase.getVersion();
            if (StringUtils.isNotBlank(cubeBase.getOwner())) {
                for (String owner : cubeBase.getOwner().split(",")) {
                    String ownerName = owner.substring(owner.indexOf("(") + 1, owner.length() - 1);
                    String realName = owner.substring(0, owner.indexOf("("));
                    RocUser rocUser = new RocUser(ownerName, realName);
                    owners.put(ownerName, rocUser);
                }
            }
            //原始数据有数据
            String modifiedTime = DateFormatUtils.format(cubeBase.getUpdateTime(), "yyyy-MM-dd HH:mm:ss");
            if (cubeMap.containsKey(authCubeName)) {
                if (!isDateEquals(cubeMap.get(authCubeName).get(0).getLastModified(), modifiedTime)) {
                    //将数据库原有数据放进待删除列表
                    delAuthCubes.addAll(cubeMap.get(authCubeName));
                } else {
                    // cubeMap移除
                    cubeMap.remove(authCubeName);
                    //跳过本次循环
                    continue;
                }
                // cubeMap移除
                cubeMap.remove(authCubeName);
            }
            KylinCube kc=kylinCubeRepository.getByNameAndDeleted(authCubeName, 0);
            if(kc==null){
                continue;
            }
            String authCubeId = kc.getId();
            if (StringUtils.isNotBlank(cubeBase.getOwner())) {
                String projectId = projects.get(cubeBase.getProjectName());
                if (StringUtils.isEmpty(projectId)) {
                    KylinProject kp=kylinProjectRepository.getByNameAndDeleted(cubeBase.getProjectName(), 0);
                    if(kp==null){
                        continue;
                    }
                    projectId =kp.getId();
                }
                CubeInfo cubeInfo;
                try {
                    cubeInfo = cubeStep4Service.getInfo(cubeBase.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                    cubeInfo = new CubeInfo();
                }
                for (String owner : cubeBase.getOwner().split(",")) {
                    String ownerName = owner.substring(owner.indexOf("(") + 1, owner.length() - 1);
                    String realName = owner.substring(0, owner.indexOf("("));
                    RocAuthCube authCube;
                    if(StringUtils.isEmpty(cubeInfo.getCreator())){
                         authCube = new RocAuthCube(ownerName, realName, authCubeId,cubeBase.getCubeNameCh(),projectId, cubeBase.getProjectName(), DateFormatUtils.format(cubeBase.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"), authCubeName);
                    }else{
                         authCube = new RocAuthCube(ownerName, realName, authCubeId,cubeBase.getCubeNameCh(),projectId, cubeBase.getProjectName(), DateFormatUtils.format(cubeBase.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"), authCubeName
                                ,cubeInfo.getCreator().substring(cubeInfo.getCreator().indexOf("(") + 1, cubeInfo.getCreator().length() - 1),cubeInfo.getCreator().substring(0, owner.indexOf("(")),
                                cubeInfo.getCycle().getValue(),
                                cubeInfo.getModifier().substring(cubeInfo.getModifier().indexOf("(") + 1, cubeInfo.getModifier().length() - 1),
                                cubeInfo.getModifier().substring(0, owner.indexOf("(")));
                    }
                    authCubes.add(authCube);
                }
            }
        }

        for (String key : cubeMap.keySet()) {
            delAuthCubes.addAll(cubeMap.get(key));
        }

        if (delAuthCubes.size() != 0) {
            //删除roc_auth_cube表数据
            rocAuthCubeRepository.deleteInBatch(delAuthCubes);
        }
        if (authCubes.size() != 0) {
            //添加roc_auth_cube表数据
            rocAuthCubeRepository.saveAll(authCubes);
        }
        if (authProjects.size() != 0 || authCubes.size() != 0) {
            kylinProjectRepository.updateProjectNameCh();
            kylinCubeRepository.updateCubeNameCh();
            //用户
            owners.forEach((key, value) -> {
                rocUsers.add(value);
            });
            rocUserRepository.deleteAll();
            //保存用户
            rocUserRepository.saveAll(rocUsers);
        }

    }

    public static boolean isDateEquals(String d1, String d2) {
        return d2.compareTo(d1) == 0 ? true : false;
    }
}
